import React, { useState, useEffect } from 'react'
import { DndContext, PointerSensor, useSensor, useSensors } from '@dnd-kit/core'
import { restrictToVerticalAxis } from '@dnd-kit/modifiers'
import {
  arrayMove,
  SortableContext,
  useSortable,
  verticalListSortingStrategy
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import './index.modules.scss'
import { baseURL } from '@/http/request'
import debounce from '@/components/js/throttle'
import SearchView from '@/components/searchView/index'
import {
  Space,
  Table,
  Button,
  Image,
  Modal,
  Card,
  message,
  Form,
  Upload,
  Input,
  Popconfirm,
  Pagination
} from 'antd'
import { DeleteOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons'
import {
  carBrandList,
  carBrandDelete,
  carBrandAdd,
  carBrandChange,
  carBrandSerach,
  carBrandCreateExcel,
  carBrandSort
} from '@/http/api/carBrand'
let pageData = {
  page: 1,
  size: 10,
  total: 0
}
let typeList = [
  {
    title: '汽车品牌',
    type: 'inpute',
    model: 'name'
  },
  {
    title: '汽车型号',
    type: 'inpute',
    model: 'carType'
  }
]
const Row = (props) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({
    id: props['data-row-key']
  })
  const style = {
    ...props.style,
    transform: CSS.Translate.toString(transform),
    transition,
    cursor: 'move',
    ...(isDragging
      ? {
          position: 'relative',
          zIndex: 9999
        }
      : {})
  }
  return (
    <tr
      {...props}
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
    />
  )
}
let _id = ''
let selectedRowsdata = []
let firstList = []
const App = React.forwardRef((props, ref) => {
  const [messageApi, contextHolder] = message.useMessage()
  useEffect(() => {
    getList()
  }, [])
  const handleChildMethod = () => {
    getList()
  }

  React.useImperativeHandle(ref, () => ({
    handleChildMethod
  }))
  const { TextArea } = Input
  const [dataSource, setDataSource] = useState([])
  const [isShowAdd, serIsShowAdd] = useState(false)
  const [form] = Form.useForm()
  const [fileList, setFileList] = useState([])
  const [magnifyImg, setMagnifyImg] = useState('')
  const [isImgShow, setIsImgShow] = useState(false)
  const columns = [
    {
      title: '品牌图片',
      dataIndex: 'image',
      align: 'center',
      render: (image) => {
        return (
          <Image
            width={60}
            height={60}
            src={image}
            fallback=""
          />
        )
      }
    },
    {
      title: '车辆品牌',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: 'A3',
      dataIndex: 'A3',
      align: 'center',
      render: (A3) => {
        return <div>{JSON.parse(A3)?.join(',')}</div>
      }
    },
    {
      title: 'A5',
      dataIndex: 'A5',
      align: 'center',
      render: (A5) => {
        return <div>{JSON.parse(A5)?.join(',')}</div>
      }
    },
    {
      title: 'A7',
      dataIndex: 'A7',
      align: 'center',
      render: (A7) => {
        return <div>{JSON.parse(A7)?.join('')}</div>
      }
    },
    {
      title: 'A8',
      dataIndex: 'A8',
      align: 'center',
      render: (A8) => {
        return <div>{JSON.parse(A8)?.join('')}</div>
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              changeClickFn(data)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            placement="top"
            onConfirm={() => {
              DeleteFn(data)
            }}
            onCancel={() => {
              message.error('取消删除')
            }}
            okText="是"
            cancelText="不"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]
  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 1
      }
    })
  )
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      selectedRowsdata = selectedRows.map((item) => {
        return item._id
      })
    }
  }
  // 获取列表
  const getList = async () => {
    pageData.appid = localStorage.getItem('appid')
    const res = await carBrandList(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    firstList = res.data.res
    pageData.total = res.data.total
  }
  const onDragEnd = ({ active, over }) => {
    let dataList = []
    if (active.id !== over?.id) {
      setDataSource((prev) => {
        const activeIndex = prev.findIndex((i) => i.key === active.id)
        const overIndex = prev.findIndex((i) => i.key === over?.id)
        dataList = arrayMove(prev, activeIndex, overIndex)
        return arrayMove(prev, activeIndex, overIndex)
      })
    }
    debounce(() => {
      sortFn(dataList)
    }, 100)
  }
  // 点击编辑
  const changeClickFn = (data) => {
    let addDAta = { ...data }
    setFileList([data.image])
    addDAta.A3 = JSON.parse(data.A3)
    addDAta.A5 = JSON.parse(data.A5)
    addDAta.A7 = JSON.parse(data.A7)
    addDAta.A8 = JSON.parse(data.A8)
    addDAta.remark = []
    console.log(addDAta.A8)
    for (const key in addDAta) {
      if (key == 'A3' || key == 'A5' || key == 'A7' || key == 'A8') {
        if (Array.isArray(addDAta[key])) {
          addDAta[key].forEach((item) => {
            addDAta.remark.push(`${item}/${key}`)
          })
        }
      }
    }
    addDAta.remark = addDAta.remark.join('\n')
    if (addDAta._id) {
      form.setFieldsValue(addDAta)
      _id = addDAta._id
    }
    serIsShowAdd(true)
  }
  // 排序
  const sortFn = async (data) => {
    let ids = []
    let sort = []
    data.forEach((item, index) => {
      ids.push(item._id)
      sort.push(firstList[index].sort)
    })
    await carBrandSort({ id: ids, sort })
  }
  // 添加
  const onFinish = async (data) => {
    let res = ''
    data.appid = localStorage.getItem('appid')
    data.image = fileList[0]
    if (_id) {
      data._id = _id

      res = await carBrandChange(data)
    } else {
      res = await carBrandAdd(data)
    }
    if (res.data.type == 1) {
      messageApi.success(res.data.message)
    } else {
      messageApi.error(res.data.message)
    }
    getList()
    serIsShowAdd(false)
    form.resetFields()
    setFileList([])
    _id = ''
  }
  const pageChangeFn = (page, pageSize) => {
    pageData.page = page
    pageData.size = pageSize
    getList()
  }
  const porpsData = async (data) => {
    pageData = {
      page: 1,
      size: 10,
      total: 0,
      appid: localStorage.getItem('appid'),
      ...data
    }
    const res = await carBrandSerach(pageData)
    setDataSource(
      res.data.res.map((item) => {
        return {
          ...item,
          key: item._id
        }
      })
    )
    pageData.total = res.data.total
  }
  // 删除照片
  const deleteImgFn = (index) => {
    let imgData = [...fileList]
    imgData.splice(index, 1)
    setFileList(imgData)
  }
  const imgageChangeFn = (data) => {
    if (data.file.status == 'done') {
      setFileList([
        ...fileList,
        ...data.fileList.map((item) => {
          return item.response.image_url
        })
      ])
    }
  }
  // 删除
  const DeleteFn = async (data) => {
    const res = await carBrandDelete({ id: data._id })
    messageApi.success(res.data.message)
    getList()
  }
  // 导出
  const exportExcel = async () => {
    let data = {
      id: 'all',
      appid: localStorage.getItem('appid')
    }
    if (selectedRowsdata.length != 0) {
      data.id = selectedRowsdata
    }
    const res = await carBrandCreateExcel(data)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const a = document.createElement('a')
    a.href = url
    a.download = '车型.xlsx'
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
  }
  return (
    <div>
      <Card>
        <SearchView typeList={typeList} porpsData={porpsData}></SearchView>
        <div className="headerButton">
          <Button
            style={{ marginRight: '10px' }}
            type="primary"
            onClick={() => {
              serIsShowAdd(true)
            }}
          >
            新增品牌型号
          </Button>
          <Button
            type="primary"
            onClick={() => {
              exportExcel()
            }}
          >
            导出车辆信息
          </Button>
        </div>
        <DndContext
          sensors={sensors}
          modifiers={[restrictToVerticalAxis]}
          onDragEnd={onDragEnd}
        >
          <SortableContext
            items={dataSource.map((i) => i.key)}
            strategy={verticalListSortingStrategy}
          >
            <Table
              rowSelection={{
                type: 'checkbox',
                ...rowSelection
              }}
              pagination={false}
              bordered
              components={{
                body: {
                  row: Row
                }
              }}
              rowKey="key"
              columns={columns}
              dataSource={dataSource}
            />
          </SortableContext>
        </DndContext>
        <div className="Pagin">
          <Pagination
            onChange={pageChangeFn}
            defaultCurrent={pageData.page}
            total={pageData.total}
          />
        </div>
      </Card>
      <div>
        <Modal
          title="添加"
          footer={[]}
          onCancel={() => {
            serIsShowAdd(false)
            form.resetFields()
            setFileList([])
            _id = ''
          }}
          open={isShowAdd}
        >
          <Form
            labelCol={{
              span: 5
            }}
            wrapperCol={{
              span: 14
            }}
            layout="horizontal"
            style={{
              maxWidth: 800
            }}
            form={form}
            onFinish={onFinish}
          >
            <Form.Item
              label="车标logo"
              name="image"
              rules={[
                {
                  required: true,
                  message: '请选择图片'
                }
              ]}
            >
              <div>
                <div className="upImgBox align_center">
                  {fileList.length == 0 ? (
                    <Upload
                      maxCount={1}
                      action={baseURL + 'api/uploadAvatar'}
                      listType="picture-card"
                      accept=".png,.jpg"
                      onChange={imgageChangeFn}
                    >
                      <button
                        style={{
                          border: 0,
                          background: 'none'
                        }}
                        type="button"
                      >
                        <PlusOutlined />
                        <div
                          style={{
                            marginTop: 8
                          }}
                        ></div>
                      </button>
                    </Upload>
                  ) : (
                    fileList.map((item, index) => {
                      return (
                        <div key={index} className="imgBox center">
                          <img
                            style={{ width: '100%', height: '100%' }}
                            src={item}
                            alt=""
                          />
                          <div
                            className="mask center"
                            style={{ justifyContent: 'space-evenly' }}
                          >
                            <DeleteOutlined
                              onClick={() => {
                                deleteImgFn(index)
                              }}
                              style={{ fontSize: 20, color: '#FFFFFF' }}
                            />
                            <EyeOutlined
                              onClick={() => {
                                setMagnifyImg(item)
                                setIsImgShow(true)
                              }}
                              style={{ fontSize: 20, color: '#FFFFFF' }}
                            />
                          </div>
                        </div>
                      )
                    })
                  )}
                </div>
              </div>
            </Form.Item>
            <Form.Item
              label="品牌名称："
              name="name"
              rules={[
                {
                  required: true,
                  message: '请输入名称'
                }
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="型号"
              name="remark"
              rules={[
                {
                  required: true,
                  message: '请输入型号'
                }
              ]}
            >
              <TextArea
                rows={4}
                placeholder="请输入车辆型号-车型，型号之间用”、“隔开"
              />
            </Form.Item>
            <Form.Item
              wrapperCol={{
                offset: 6,
                span: 16
              }}
            >
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                type="primary"
                onClick={() => {
                  form.resetFields()
                  serIsShowAdd(false)
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {/* 图片放大效果 */}
      <Modal
        open={isImgShow}
        footer={[]}
        onCancel={() => {
          setIsImgShow(false)
        }}
        closable={false}
      >
        <div>
          <img className="ImgShow" src={magnifyImg} alt="" srcset="" />
        </div>
      </Modal>
      {contextHolder}
    </div>
  )
})
export default App
